#!/bin/sh
# PCP QA Test No. 1178
# Exercise the BCC PMDA tcpperpid module - install, remove and values.
#
# Copyright (c) 2018 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.bcc

_pmdabcc_check
which curl >/dev/null 2>&1 || _notrun "No curl binary installed"
[ "$(pmpython src/bcc_version_check.python)" = "0.6.1" ] \
  && _notrun "Broken BCC version detected"
case "`uname -srm`"
in
    Linux\ 5.2.*)
    		_notrun "Bad Linux 5.2 kernel headers will cause BPF to fail"
		;;
esac

target_ip=1.1.1.1

status=1       # failure is the default!
signal=$PCP_BINADM_DIR/pmsignal

# Some combinations of distro and kernel are known to be "bad"
# for some BPF modules
#
kernel=`uname -r`
echo "$kernel" >>$seq_full
case `admin/whatami`
in
    *Fedora\ 32\ *)
	_notrun "bcc tcpperpid module will not compile on Fedora 32"
	;;
    *Ubuntu\ 19.10\ *)
	_notrun "bcc tcpperpid module will not compile on Ubuntu 19.10"
	;;
    *Ubuntu\ 20.04\ *)
	# works on 5.4 kernel, not on 5.8.0-1033-azure
	#
	case "$kernel"
	in
	    5.8.0-*-azure)
		_notrun "bcc tcpperpid module will not compile on Ubuntu kernel $kernel"
		;;
	esac
	;;
    *openSUSE\ Leap\ 15.1\ *)
	_notrun "bcc tcpperpid module will not compile on openSUSE 15.1"
	;;
esac

_install_filter()
{
    sed \
    -e "s/Using BPF source file .\+/Using BPF source file X/g" \
    #end
}

cat <<EOF >$tmp.conf
# Installed by PCP QA test $seq on `date`
[pmda]
modules = tcpperpid
prefix = bcc.
[tcpperpid]
module = tcpperpid
cluster = 11
dport = 80
EOF

_pmdabcc_try_compile $tmp.conf

_prepare_pmda bcc
trap "_pmdabcc_cleanup; exit \$status" 0 1 2 3 15
_stop_auto_restart pmcd

_pmdabcc_install <$tmp.conf | _install_filter
_pmdabcc_wait_for_metric

# Generate system activity for the BCC tcpperpid module
curl -s http://${target_ip} > /dev/null &
curlpid=$!

pmsleep 3

echo "=== report metric values ==="
pminfo -dfmtT bcc.proc.io.net.total.rx 2>&1 | grep $curl_pid\" | tee -a $seq_full \
| _value_filter_nonzero >$tmp.1
if grep OK <$tmp.1 >/dev/null
then
    cat $tmp.1
else
    # Twice as the old kprobe based BPF seems to provide
    # results occasionally with some delay.
    # Safe to remove when no kernel < 4.16 / bcc < 0.6 in use anywhere
    pmsleep 2
    pminfo -dfmtT bcc.proc.io.net.total.rx 2>&1 | grep $curl_pid\" | tee -a $seq_full \
    | _value_filter_nonzero >$tmp.2
    if grep OK <$tmp.2 >/dev/null
    then
	cat $tmp.2
    else
	cat $tmp.1
	cat $tmp.2
    fi
fi

_pmdabcc_remove

status=0
exit
